import { AppType } from "@/Util/Constant"
import * as PIXI from 'pixi.js'
import { PixiBase } from "./baseClass/PixiBase";
import { Broadcaster, DataChange, EventType } from "./broadcaster/Broadcaster";
import Hlddz from "./model/hlddz";
import eventBus from "@/Util/EventBus";
import { GameStatus, SocketDataType, SocketEventType } from "@/share/commonType";
import socket from "@/socket/UserChatSocket";
let TextureCache = PIXI.utils.TextureCache

// 参考洛书，监听者都是有model的实例的。
export class Background extends PixiBase {
    model: Hlddz = Hlddz.getInstance()
    constructor(app: AppType) {
        super(app)
        this.addListener(this.model)
        this.bindEvent(this.baseContainer, 'click', this.clickHandler)
    }

    changeBg(bgName: string) {
        let bgTexture = TextureCache[bgName]
        let bgSprite = new PIXI.Sprite(bgTexture);
        bgSprite.width = this.app.screen.width
        bgSprite.height = this.app.screen.height
        this.baseContainer.addChild(bgSprite)
    }
    notify(caster: Broadcaster, event: EventType): void {
        let action = event.action
        switch (action) {
            case DataChange.FinishLoad:
                this.finishLoad()
                break;

            default:
                break;
        }
    }
    clickHandler = (e: any) => {
        let posX = e.client.x
        let posY = e.client.y
        if (posY < 55 && posX > window.innerWidth - 55) {
            // 销毁实例之前广播用户退出游戏的消息, 用于掉线通知，或者退出桌面
            let hlddz = Hlddz.getInstance()
            let socketMsg = {
                action: SocketEventType.DdzGame,
                dataType: SocketDataType.QuitGame,
                data: {
                    gameid: hlddz.gameId,
                    username: hlddz.userinfo.username
                }
            }
            socket.emit(socketMsg)
            eventBus.emit('back-home')
        }
    }
    finishLoad = () => {
        this.changeBg('game-bg')
    }
}